// const chalk = require('chalk');
// const logger = require('../logger')("config:mgr");
// const pkgUp = require('pkg-up');
const { cosmiconfigSync } = require('cosmiconfig');// 该依赖支持许多不同方面的配置处理，例如附加文件格式、异步搜索、缓存等
const configLoader = cosmiconfigSync('settings');// 加载的配置文件名 xxx.config.js  settings.config.js

// 使用ajv对配置文件参数格式进行限定
const betterAjvErrors = require('better-ajv-errors').default;// 改依赖可以使 ajv校验异常信息更方便阅读
const schema = require('./schema.json');
const Ajv = require('ajv').default;
const ajv = new Ajv();
const { exit } = require('process');



module.exports = function getConfig() {
    // const pkgPath = pkgUp.sync({cwd: process.cwd()});
    // const pkg = require(pkgPath);
    const result = configLoader.search(process.cwd());
    if (!result) {
        // console.log(chalk.yellow('Could not find configuration, using default'));
        console.log('加载配置文件失败');
        exit(1);
        return null;
    } else {
        const isValid = ajv.validate(schema,result.config);
        if(!isValid){
            // console.log(chalk.yellow('Invalid configuration was supplied'));
            console.log('配置文件参数校验失败');

            // console.log(ajv.errors);
            console.log();
            // @todo 自定义schema app、cmd、fileName 正则？
            console.log(betterAjvErrors(schema,result.config,ajv.errors));
            process.exit(1);
        }

        // console.log('加载配置文件成功', result.config);
        return result.config;
    }
}